<script setup lang="ts">
import type {LoginReq} from "@/interface/user.ts"
import {User,Lock} from "@element-plus/icons-vue"
import {reactive, ref} from 'vue'
import type {FormInstance,FormRules} from "element-plus"
import {useLoginApi}from '@/services/api'
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import {useStore} from "vuex"

const model:LoginReq = reactive({
  username:"",
  password:""
})
const router = useRouter()
const store = useStore()
const loginRef = ref<FormInstance>()
const loginRules = ref<FormRules>({
  username:[
    {
      required:true,
      message:"账号不能为空",
      trigger:'blur'
    }
  ],
  password:[
    {
      required:true,
      message:"密码不能为空",
      trigger:'blur'
    }
  ]
})
const submit = (formEl: FormInstance | undefined)=>{
  if(!formEl) return
  formEl.validate(async (isValid: boolean) => {
    if (isValid) {
      const { data: res } = await useLoginApi(model)
      if(!res || !res.target){
        ElMessage.success("登录成功")
        await store.dispatch("auth/setToken",res.token)
        await store.dispatch("auth/setUserName",res.username)
        await store.dispatch("auth/setUserId",res.userId)
        await router.push("/index")
      }
    } else {
      return
    }
  })
}
</script>

<template>
<el-form class="login-form" :model="model" ref="loginRef" :rules="loginRules">
  <h1 class="login-title">登录</h1>
  <el-form-item prop="username">
    <el-input type="text" placeholder="请输入账号" :perfix-icon="User" v-model="model.username" size="large"></el-input>
  </el-form-item>
  <el-form-item prop="password">
    <el-input show-password type="password" placeholder="请输入密码" :perfix-icon="Lock" v-model="model.password" size="large"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" class="login-button" size="large" @click="submit(loginRef)">登录</el-button>
  </el-form-item>
</el-form>
</template>

<style scoped>
.login-form{
  grid-row: 1;
  grid-column: 1;
  opacity: 1;
  transition: 1s ease-in-out;
  transition-delay: 0.5s;
  padding: 1% 25%;
  z-index: 1;
}
.login-form.sign-up-model{
  opacity: 0;
  transition: 1s ease-in-out;
  z-index: 0;
}
.login-title{
  text-align: center;
  color:#444;
}
.login-button{
  width: 100%;
  font-size: 18px;
}
</style>